﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.Office.DocumentManagement.MetadataNavigation;
using System.Collections.Generic;

namespace MS.InformationManagement.Documents.ObjectDef.ItemReceivers.MetadataNavigation
{
    /// <summary>
    /// List Events
    /// </summary>
    public class NavigationReceiver : SPListEventReceiver
    {
       /// <summary>
       /// A list was added
       /// </summary>
       public override void ListAdded(SPListEventProperties properties)
       {
           base.ListAdded(properties);
           EventFiringEnabled = false;
           SPList targetList = properties.List;
           SPWeb currentWeb = properties.Web;
           currentWeb.AllowUnsafeUpdates = true;
           if (properties.TemplateId.Equals(10008))
           {

               //Setting navigation
               MetadataNavigationSettings navSettings = MetadataNavigationSettings.GetMetadataNavigationSettings(targetList);

               navSettings.ClearConfiguredHierarchies();
               navSettings.ClearConfiguredKeyFilters();

               navSettings.AddConfiguredHierarchy(new MetadataNavigationHierarchy(currentWeb.Fields[new Guid("{E3F74F1D-EA2E-4B97-87FD-74207EEF7079}")]));
               navSettings.AddConfiguredHierarchy(new MetadataNavigationHierarchy(currentWeb.Fields[new Guid("{C2940074-06DD-40D2-B67D-D1E02C50FC87}")]));
               navSettings.AddConfiguredHierarchy(new MetadataNavigationHierarchy(currentWeb.Fields[new Guid("{0E504087-E0AD-4723-82A7-93C8BBDB5E3D}")]));
               MetadataNavigationSettings.SetMetadataNavigationSettings(targetList, navSettings, true);
               targetList.RootFolder.Update();
               targetList.Update();


               //Setting contenttypes order
               List<SPContentType> listContentTypes = new List<SPContentType>();
               SPContentType archiveContentType = null;
               for (int i = 0; i < targetList.ContentTypes.Count; i++)
               {
                   if (targetList.ContentTypes[i].Name != "Archivo")
                       listContentTypes.Add(targetList.ContentTypes[i]); 
                   else
                       archiveContentType = targetList.ContentTypes[i];
               }
               listContentTypes.Insert(0, archiveContentType);
               targetList.RootFolder.UniqueContentTypeOrder = listContentTypes;
               targetList.NavigateForFormsPages = true;
               targetList.RootFolder.Update();
               targetList.Update();


           }
           currentWeb.AllowUnsafeUpdates = false;
           EventFiringEnabled = true;
           
       }


    }
}
